package com.cheney.weiboo.view;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.cheney.weiboo.R;
import com.cheney.weiboo.domain.Users;
import com.cheney.weiboo.service.UserService;
import com.cheney.weiboo.utils.TextUtil;
import com.cheney.weiboo.utils.WeiboContext;
import com.mime.qweibo.examples.MyWeiboSync;

public class AddWeiBoActivity extends Activity implements OnClickListener{
	
	private ImageView addPic;
	private ImageView addAt;
	private ImageView addTopic;
	private ImageView addEmo;
	private ImageView location;
	private Button send;
	private MyWeiboSync weibo;
	private Handler handler;
	private String userId;
	private UserService userService;
	private RelativeLayout add_weibo_head;
	private EditText content;
	private Users user;
	private RelativeLayout relativeLayout;
	private EditText atEditText;
	private Button atButton;
	private ListView atListView;
	private ExecutorService executorService;
	private int THREAD_SIZE = 3;
	private JSONObject jsonObject;
	private JSONArray array;
	private List<String> atList;
	private List<String> matchList;
	private ArrayAdapter<String> arrayAdapter;
	private FrameLayout operation_layout;
	private List<Map<String,Object>> expressionList;
	private ExpressionAdapter expressionAdapter;
	private GridView gridView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.addweibo);
		setUpView();
		setUpListeners();
		weibo = WeiboContext.getInstance();
		SharedPreferences sp = getSharedPreferences("default_users",Activity.MODE_PRIVATE);
		userId = sp.getString("user_default_name", "");
		userService = new UserService(getApplicationContext());
		handler = new addWeiboHandler();
		executorService.submit(new AtThread());
		
		
	}
	//设置VIEW
	public void setUpView(){
		addPic = (ImageView)findViewById(R.id.add_pic);
		addAt = (ImageView)findViewById(R.id.add_at);
		addTopic = (ImageView)findViewById(R.id.add_topic);
		addEmo = (ImageView)findViewById(R.id.add_emo);
		location = (ImageView)findViewById(R.id.add_location);
		send = (Button)findViewById(R.id.send);
		content = (EditText)findViewById(R.id.addweibo_content);
		operation_layout = (FrameLayout)findViewById(R.id.operation_layout);
		add_weibo_head = (RelativeLayout)findViewById(R.id.addweibo_head);
		
		executorService = Executors.newFixedThreadPool(THREAD_SIZE);
		atList = new ArrayList<String>();
		
		expressionList = buildExpressionsList();
		expressionAdapter = new ExpressionAdapter(AddWeiBoActivity.this,expressionList);
		View view = (View)LayoutInflater.from(AddWeiBoActivity.this).inflate(R.layout.addweibo_emo, null);
		gridView = (GridView)view.findViewById(R.id.add_grid);
		gridView.setAdapter(expressionAdapter);
		
		relativeLayout = (RelativeLayout)LayoutInflater.from(AddWeiBoActivity.this).inflate(R.layout.addweibo_at, null);
		atButton = (Button)relativeLayout.findViewById(R.id.at_btn);
		atListView = (ListView)relativeLayout.findViewById(R.id.at_listview);
		atEditText = (EditText)relativeLayout.findViewById(R.id.at_content);
		
	}
	
	//创建handler
	class addWeiboHandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			int size = array.length();
			for(int i=0;i<size;i++){
				JSONObject data = array.optJSONObject(i);
				try {
					atList.add(data.getString("nick")+"("+data.getString("name")+")");
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			matchList = new ArrayList();
			matchList.addAll(atList);
			Log.d("listSize", ""+atList.size());
			arrayAdapter = new ArrayAdapter<String>(AddWeiBoActivity.this,R.layout.at_item,R.id.at_nick_name,atList);
			atListView.setAdapter(arrayAdapter);
			
		}
	}
	
	//设置Listeners
	public void setUpListeners(){
		send.setOnClickListener(this);
		addAt.setOnClickListener(this);
		addPic.setOnClickListener(this);
		addTopic.setOnClickListener(this);
		addEmo.setOnClickListener(this);
		location.setOnClickListener(this);
		atListView.setOnItemClickListener(new AtListItemListener());
		gridView.setOnItemClickListener(new GridViewItemListener());
	}
	
	class AtThread extends Thread{
		@Override
		public void run() {
			String str = weibo.getFans(weibo.getAccessTokenKey(), weibo.getAccessTokenSecrect(), 50, 0, userId);
			Log.d("Fans", ""+str);
			try {
				 jsonObject = new JSONObject(str).getJSONObject("data");
				 array = jsonObject.getJSONArray("info");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			 Message message = handler.obtainMessage();
			 handler.sendMessage(message);
		}
		
	}
	
	@Override
	public void onClick(View view) {
		
		if(operation_layout.getChildCount()>0){
			operation_layout.removeAllViews();
			operation_layout.setVisibility(View.GONE);
			add_weibo_head.setVisibility(View.VISIBLE);
			content.setVisibility(View.VISIBLE);
		}
		switch(view.getId()){
		//点击发送按钮
		case R.id.send : {
			String returnStr = null;
			returnStr = weibo.publishMsg(weibo.getAccessTokenKey(), weibo.getAccessTokenSecrect(), content.getText().toString());
			try {
				JSONObject jsonObject = new JSONObject(returnStr);
				if("ok".equals(jsonObject.get("msg"))){
					Toast.makeText(AddWeiBoActivity.this,"发布成功", Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.d("发送按钮", ""+returnStr);
		}
		break;
		case R.id.add_at :{
			//删除Layout上面的所有VIEW
			Log.d("@", "@");
		//	relativeLayout.removeAllViews();
			atEditText.setText("@");
			operation_layout.addView(relativeLayout);
			
			add_weibo_head.setVisibility(View.GONE);
			content.setVisibility(View.GONE);
			
			operation_layout.setVisibility(View.VISIBLE);
		}
		break;
		case R.id.add_pic:{
			operation_layout.removeAllViews();
			operation_layout.setVisibility(View.GONE);
			add_weibo_head.setVisibility(View.VISIBLE);
			content.setVisibility(View.VISIBLE);
		}
		break;
		case R.id.add_emo:{
			operation_layout.removeAllViews();
			operation_layout.addView(gridView);
			
			add_weibo_head.setVisibility(View.GONE);
			content.setVisibility(View.GONE);
			operation_layout.setVisibility(View.VISIBLE);
		}
		break;
	  }
	}
	
	/**
	 * 构建表情的list
	 */
	private List<Map<String,Object>> buildExpressionsList(){
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		DecimalFormat df = new DecimalFormat("000");
		for(int i=0;i<105;i++){
			Map<String,Object> map = new HashMap<String,Object>();
			String name = "h"+df.format(i);
            //获得文件内容
			int id = getResources().getIdentifier(name, "drawable", getApplicationContext().getPackageName());
			//根据文件ID获得drawable
			Drawable drawable = getResources().getDrawable(id);
			map.put("drawableId", name);
			map.put("drawable", drawable);
			list.add(map);
		}
		return list;
	}
	
	class ExpressionAdapter extends BaseAdapter{
		
		private Context context;
		private LayoutInflater inflater;
		List<Map<String,Object>> list;
		public ExpressionAdapter(Context context,List<Map<String,Object>> list){
			this.context = context;
			this.list = list;
			this.inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Map<String,Object> map = list.get(position);
			ImageView iv = new ImageView(context);
			iv.setImageDrawable((Drawable)map.get("drawable"));
			return iv;
		}
		
		
	}
	
	//处理表格的点击事件
	class GridViewItemListener implements OnItemClickListener{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
			Log.d("表情", "");
			Map<String, Object> map = expressionList.get(position);
			String drawableId = (String)map.get("drawableId");
			add_weibo_head.setVisibility(View.VISIBLE);
			content.setVisibility(View.VISIBLE);
			content.setText(content.getText()+"/"+TextUtil.drawableIdToFaceName.get(drawableId));
			operation_layout.removeAllViews();
			operation_layout.setVisibility(View.GONE);
		}
		
	}
	
	class AtListItemListener implements OnItemClickListener{
		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long arg3) {
			add_weibo_head.setVisibility(View.VISIBLE);
			content.setVisibility(View.VISIBLE);
			String str = matchList.get(position);
			operation_layout.removeAllViews();
			operation_layout.setVisibility(View.GONE);
			String nick = str.substring(0, str.indexOf("("));
			content.setText(content.getText()+"@"+nick);
		}
		
	}
}

